package com.door.erp.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.door.erp.dwz.DwzResponse;
import com.door.erp.enums.BaseInfoStatus;
import com.door.erp.model.PurchaseOrder;
import com.door.erp.pager.Pager;
import com.door.erp.sevice.MaterialService;
import com.door.erp.sevice.PurchaseOrderService;
import com.door.erp.sevice.SupplierService;

@Controller
public class PurchaseOrderController {

	@Resource(name="purchaseOrderService", type=PurchaseOrderService.class)
	private PurchaseOrderService purchaseOrderService;
	
	@Resource(name="materialService", type=MaterialService.class)
	private MaterialService materialService;
	
	@Resource(name="supplierService", type=SupplierService.class)
	private SupplierService supplierService;
	
	@RequestMapping("/purchaseorder/add.do")
	public ModelAndView add(PurchaseOrder purchaseOrder) {
		purchaseOrder.setCreateTime(new Date());
		purchaseOrder.setStatus(BaseInfoStatus.NORMAL);
		purchaseOrderService.add(purchaseOrder);
		ModelAndView mav = new ModelAndView("dwzresponse");
		DwzResponse resonse = new DwzResponse();
		resonse.setNavTabId("purchaseorder");
		resonse.setMessage("添加成功");
		mav.addObject("response", resonse);
		return mav;
	}
	
	@RequestMapping("/purchaseorder/addPage.do")
	public String addPage(HttpServletRequest request) {
		return "purchaseorder/add";
	}
	
	@RequestMapping("/purchaseorder/purchaseorders.do")
	public String purchaseOrders(HttpServletRequest request, Pager pager) {
		if(pager == null) {
			pager = new Pager();
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status", BaseInfoStatus.NORMAL);
		int totalCount = purchaseOrderService.getCount(params);
		pager.setTotalCount(totalCount);
		List<PurchaseOrder> purchaseOrders = purchaseOrderService.getAll(params, pager);
		request.setAttribute("purchaseorders", purchaseOrders);
		request.setAttribute("pager", pager);
		return "purchaseorder/purchaseorders";
	}
	
	@RequestMapping("/purchaseorder/delete.do")
	public ModelAndView delete(long id) {
		PurchaseOrder purchaseOrder = purchaseOrderService.getObject(id);
		purchaseOrder.setStatus(BaseInfoStatus.DELETED);
		purchaseOrderService.modify(purchaseOrder);
		ModelAndView mav = new ModelAndView("dwzresponse");
		DwzResponse resonse = new DwzResponse();
		resonse.setNavTabId("purchaseorder");
		resonse.setCallbackType("");
		resonse.setMessage("删除采购单成功");
		mav.addObject("response", resonse);
		return mav;
	}
	
	@RequestMapping("/purchaseorder/getPurchaseOrder.do")
	public String getPurchaseOrder(HttpServletRequest request, long id) {
		PurchaseOrder purchaseOrder = purchaseOrderService.getObject(id);
		request.setAttribute("purchaseorder", purchaseOrder);
		return "purchaseorder/modify";
	}
	
	@RequestMapping("/purchaseorder/modify.do")
	public ModelAndView modify(PurchaseOrder purchaseOrder) {
		purchaseOrderService.modify(purchaseOrder);
		ModelAndView mav = new ModelAndView("dwzresponse");
		DwzResponse resonse = new DwzResponse();
		resonse.setNavTabId("purchaseorder");
		resonse.setMessage("修改成功");
		mav.addObject("response", resonse);
		return mav;
	}
	
	@RequestMapping("/purchaseorder/exportPage.do")
	public String exportPage(HttpServletRequest request) {
		return "purchaseorder/export";
	}
	
	@RequestMapping("/purchaseorder/export.do")
	public void export(HttpServletRequest request, HttpServletResponse response) {
		String beginTimeStr = request.getParameter("beginTime");
		String endTimeStr = request.getParameter("endTime");

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		OutputStream os = null;
		
		//进行转码，使其支持中文文件名  
		String fileName = "purchase";
        try {
			fileName = java.net.URLEncoder.encode("采购报表", "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			fileName = "purchase";
			e1.printStackTrace();
		}  
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
		
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet();  
		
		HSSFCellStyle hcs = workbook.createCellStyle();
		hcs.setAlignment(HSSFCellStyle.ALIGN_LEFT);
		hcs.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		//设置列宽
		sheet.setColumnWidth(0, 2000);
		sheet.setColumnWidth(1, 8000);
		sheet.setColumnWidth(2, 5000);
		sheet.setColumnWidth(3, 4000);
		sheet.setColumnWidth(4, 2000);
		sheet.setColumnWidth(5, 2000);
		sheet.setColumnWidth(6, 3000);
		sheet.setColumnWidth(7, 4000);
		sheet.setColumnWidth(8, 7000);
		sheet.setColumnWidth(9, 6000);
		//列名
		HSSFRow head = sheet.createRow(0);
		head.setHeight((short)400);
		//序号
		HSSFCell num = head.createCell(0);
		num.setCellType(HSSFCell.CELL_TYPE_STRING);
		num.setCellValue("序号");
		HSSFCell supplier = head.createCell(1);
        supplier.setCellType(HSSFCell.CELL_TYPE_STRING);
        supplier.setCellValue("供应商");
		//原材料
        HSSFCell material = head.createCell(2);
        material.setCellType(HSSFCell.CELL_TYPE_STRING);
        material.setCellValue("材料名称");
        HSSFCell thickness = head.createCell(3);
        thickness.setCellType(HSSFCell.CELL_TYPE_STRING);
        thickness.setCellValue("规格");
        HSSFCell amount = head.createCell(4);
        amount.setCellType(HSSFCell.CELL_TYPE_STRING);
        amount.setCellValue("数量");
        HSSFCell unit = head.createCell(5);
        unit.setCellType(HSSFCell.CELL_TYPE_STRING);
        unit.setCellValue("单位");
        HSSFCell unitPrice = head.createCell(6);
        unitPrice.setCellType(HSSFCell.CELL_TYPE_STRING);
        unitPrice.setCellValue("单价");
        HSSFCell totalPrice = head.createCell(7);
        totalPrice.setCellType(HSSFCell.CELL_TYPE_STRING);
        totalPrice.setCellValue("总价");
        HSSFCell remark = head.createCell(8);
        remark.setCellType(HSSFCell.CELL_TYPE_STRING);
        remark.setCellValue("备注");
        HSSFCell createTime = head.createCell(9);
        createTime.setCellType(HSSFCell.CELL_TYPE_STRING);
        createTime.setCellValue("创建时间");
        
        List<PurchaseOrder> purchaseOrders = this.purchaseOrderService.getPurchaseOrdersByTime(beginTimeStr, endTimeStr);
        if(purchaseOrders == null) {
        	try {
    			os = response.getOutputStream();
    			workbook.write(os);
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				os.flush();
    				os.close();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
        } else {
	        int i = 1;
	        HSSFRow row = null;
	        
	        for(PurchaseOrder purchaseOrder : purchaseOrders) {
	        	row = sheet.createRow(i);
	        	row.setHeight((short)400);
	        	
	        	num = row.createCell(0);
	        	num.setCellType(HSSFCell.CELL_TYPE_STRING);
	        	num.setCellValue(String.valueOf(i));
	        	num.setCellStyle(hcs);
	        	
	        	supplier = row.createCell(1);
	            supplier.setCellType(HSSFCell.CELL_TYPE_STRING);
	            supplier.setCellValue(purchaseOrder.getSupplier().getName());
	            supplier.setCellStyle(hcs);
	            
	        	material = row.createCell(2);
	        	material.setCellType(HSSFCell.CELL_TYPE_STRING);
	            material.setCellValue(purchaseOrder.getMaterial().getName());
	            material.setCellStyle(hcs);
	            
	            thickness = row.createCell(3);
	            thickness.setCellType(HSSFCell.CELL_TYPE_STRING);
	            thickness.setCellValue(purchaseOrder.getMaterial().getStandard());
	            thickness.setCellStyle(hcs);
	            
	            amount = row.createCell(4);
	            amount.setCellType(HSSFCell.CELL_TYPE_STRING);
	            amount.setCellValue(String.valueOf(purchaseOrder.getAmount()));
	            amount.setCellStyle(hcs);
	            
	            unit = row.createCell(5);
	            unit.setCellType(HSSFCell.CELL_TYPE_STRING);
	            unit.setCellValue(purchaseOrder.getUnit());
	            unit.setCellStyle(hcs);
	            
	            unitPrice = row.createCell(6);
	            unitPrice.setCellType(HSSFCell.CELL_TYPE_STRING);
	            unitPrice.setCellValue(String.valueOf(purchaseOrder.getUnitPrice()));
	            unitPrice.setCellStyle(hcs);
	            
	            totalPrice = row.createCell(7);
	            totalPrice.setCellType(HSSFCell.CELL_TYPE_STRING);
	            totalPrice.setCellValue(String.valueOf(purchaseOrder.getTotalPrice()));
	            totalPrice.setCellStyle(hcs);
	            
	            remark = row.createCell(8);
	            remark.setCellType(HSSFCell.CELL_TYPE_STRING);
	            remark.setCellValue(purchaseOrder.getRemark());
	            remark.setCellStyle(hcs);
	            
	            createTime = row.createCell(9);
	            createTime.setCellType(HSSFCell.CELL_TYPE_STRING);
	            createTime.setCellValue(sdf.format(purchaseOrder.getCreateTime()));
	            createTime.setCellStyle(hcs);
	            
	            i++;
	        }
	        try {
				os = response.getOutputStream();
				workbook.write(os);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					os.flush();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
        }
	}
}
